<?php
namespace Tyrone\Model;
use Tyrone\Model\Base;
use Medoo\Medoo;

class TableMaxId extends Base
{

    protected $table = 'l_table_max_id';
    protected $platform;
    protected $plat_server;
    protected $where;
    public function setSid($platform = '',$plat_server = ''){
        $this->platform = $platform;
        $this->plat_server = $plat_server;
        $this->autoWhere();
        return $this;
    }
    protected function autoWhere(){
        $where = [];
        if($this->platform){
            $where['platform'] = $this->platform;
        }
        if($this->plat_server){
            $where['plat_server'] = $this->plat_server;
        }
        $this->where = $where;
    }

    protected function mergeWhere($where){
        return $this->where + $where;
    }
    public function getMaxId($tableName, $field = "value")
    {
        return $this->database->max($this->table,$field,$this->mergeWhere(['table_name'=>$tableName]));
    }

    public function updateMaxId($tableName, $value)
    {
        $data = $this->database->update($this->table,['value'=>$value],$this->mergeWhere(['table_name'=>$tableName]));
        $res = $data->rowCount() ? true : false;
        if(!$data->rowCount()){
            try{
                $this->database->insert($this->table,$this->mergeWhere([
                    "table_name" => $tableName,
                    "value" => $value
                ]));
                $res = $this->database->id() ? true : false;
            }catch(\PDOException $e){
                $res = true;
                echo $e->getTraceAsString();
            }
        }
        return $res;
    }

}